from apiflask import pagination_builder
from flask_sqlalchemy.query import Query

from ..models import Api, Role, User


def get_page(query: Query, filter_condition: dict, page: int, per_page: int, **kwargs):
    """
    根据条件查询数据，并返回分页后的数据

    :param query: 模型查询
    :param filter_condition: 查询条件
    :param page: 页数
    :param per_page: 每页数据数
    :return:
    """
    effect_filter_condition = {}
    for k, v in filter_condition.items():
        if v is not None:
            effect_filter_condition[k] = v

    pagination = query.filter_by(**effect_filter_condition).paginate(
        page=page,
        per_page=per_page,
        error_out=False
    )

    data = pagination.items
    return {
        "data": data,
        "pagination": pagination_builder(pagination, **kwargs)
    }


def get_api_query(query: dict):
    api_query = Api.query
    method = query.get("method")
    service = query.get("service")
    search = query.get("search")

    if search:
        api_query = api_query.filter((Api.url.like(f"%{search}%")) | (Api.description.like(f"%{search}%")))
    if method:
        api_query = api_query.filter(Api.method == method)
    if service:
        api_query = api_query.filter(Api.service == service)
    return api_query


def get_role_query(query: dict):
    role_query = Role.query
    service = query.get("service")
    search = query.get("search")

    if service:
        role_query = role_query.filter(Role.service == service)
    if search:
        role_query = role_query.filter((Role.name.like(f"%{search}%")) | (Role.description.like(f"%{search}%")))
    return role_query


def get_user_query(query: dict):
    user_query = User.query
    search = query.get("search")

    if search:
        user_query = user_query.filter(
            User.username.like(f"%{search}%") | User.email.like(f"%{search}%"))
    return user_query
